/** *****************************页面交互部分************************************** */


/** 根据分析类型+素材类型判断是否显示兴趣区域区域 */
function aoiAreaSet() {
    var type = $("#analysisType").val();
    
    $("#aoiArea_draw").find("a.item").css("width", $("#aoiArea_draw").width()/5.8); // 平均分布编辑区的5个按钮
    $("#aoiArea_draw").css("height","50px");

    $("#aoiArea_draw").hide();
    // $("#aoiArea_edit").hide();
    if (type == AnalysisTypeEnum.AOI) { // 首先必须要是AOI时才可能显示
        if ($("#materialType").val() != MaterialTypeEnum.RECORD && $("#materialType").val() != MaterialTypeEnum.VIDEO) {
            // 其次素材不能是录制或者视频才显示
            $("#aoiArea_draw").show();
            
            // 绑定绘制AOI区域的各个按钮方法
            $("#aoiRectButton").unbind("click");
            $("#aoiRectButton").bind("click", function() {
                initAoiDrawButtonStyle();
                $("#aoiRectButton").find("i").attr("class", "icon-aoi-rectangle-disabled");
                AoiDrawAlgorithm.draw("myCanvas",AoiTypeEnum.RECTANGLE);
            });
            $("#aoiEllipseButton").unbind("click");
            $("#aoiEllipseButton").bind("click", function() {
                initAoiDrawButtonStyle();
                $("#aoiEllipseButton").find("i").attr("class", "icon-aoi-ellipse-disabled");
                AoiDrawAlgorithm.draw("myCanvas",AoiTypeEnum.ELLIPSE);
            });
            $("#aoiDefinedButton").unbind("click");
            $("#aoiDefinedButton").bind("click", function() {
                initAoiDrawButtonStyle();
                $("#aoiDefinedButton").find("i").attr("class", "icon-aoi-polygon-disabled");
                AoiDrawAlgorithm.drawDefinedAngle("myCanvas");
            });
            $("#aoiEditButton").unbind("click");
            $("#aoiEditButton").bind("click", function() {
                initAoiDrawButtonStyle();
                $("#aoiEditButton").find("i").attr("class", "icon-aoi-edit-disabled");
                AoiDrawAlgorithm.edit("myCanvas");
            });
            $("#aoiSaveButton").unbind("click");
            $("#aoiSaveButton").bind("click", function() {
                initAoiDrawButtonStyle();
                $("#aoiSaveButton").find("i").attr("class", "icon-aoi-save-disabled");
                AoiDrawAlgorithm.save("myCanvas");
            });
        }
    }
}


/**
 * AOI兴趣区颜色下拉框初始化
 */
function initAoiDrawColors(colorObj) {
    /** 1. 增加显示的颜色 */
    var content= "<div class='aoi-info'><span class='draw-color'><i class='arrow'></i>";
    content+="<a href='#'><span class='colors c7' ><em></em></span></a>"; // 默认颜色
    content+="<div class='colorMore'><div class='colorMore-panel'>";
    content+="<a href='#'><span class='colors c0' ><em></em></span></a>";
    content+="<a href='#'><span class='colors c7' ><em></em></span></a>";
    content+="<a href='#'><span class='colors c2' ><em></em></span></a>";
    content+="<a href='#'><span class='colors c3' ><em></em></span></a>";
    
    content+="</div></div></span>";
    content+="<input type='hidden' id='cfg_aoi_color'/></div>"; // 隐藏的真正颜色
    colorObj.html(content);
    $("#cfg_aoi_color").val($(".draw-color>a>span").find("em").eq(0).css('background-color')); // 赋值隐藏的真正颜色
    changeAoiDrawColorStyle();
    
    /** 2. 绑定下拉框选择时的，显示所有颜色选项 */    
    $(".draw-color .colorMore a").unbind("hover");
    $(".draw-color").hover(function() {
        $(this).unbind("click");
        $(this).click(function() {
          /* 信息层显示 */
          var message = $(".colorMore");
          message.show();
          message.find(".colorMore-panel").stop().animate({
              top : "0px"
          }, 200);
        });
    }, function() {
        /* 信息层隐藏 */
        var message = $(".colorMore");
        message.slideUp(10, function() {
            message.find(".colorMore-panel").css("top", "-315px");
        });
        $(this).unbind("click");
    });
    
    /** 3.绑定点击a标签即选择颜色后的事件 */
    $(".draw-color .colorMore a").unbind("click");
    $(".draw-color .colorMore a").click(function() {
        $(".draw-color>a>span").attr("class", $(this).find("span").eq(0).attr("class"));
        /* 信息层隐藏 */
        var message = $(".colorMore");
        message.slideUp(10, function() {
            message.find(".colorMore-panel").css("top", "-315px");
        });

        $("#cfg_aoi_color").val($(this).find("span em").eq(0).css('background-color')); // 改变隐藏的真正颜色
        changeAoiDrawColorStyle();

    });
    
}

/**
 * AOI参数选择改变时更新
 */
function changeAoiDrawColorStyle(){
    theAoiPenColor=$("#cfg_aoi_color").val();
    theAoiFillColor=$("#cfg_aoi_color").val().colorRgba($("#cfg_aoi_diaphaneity").val());
}

/**
 * 初始化AOI绘制按钮图标样式
 */
function initAoiDrawButtonStyle(){
    $("#aoiRectButton").find("i").attr("class", "icon-aoi-rectangle");
    $("#aoiEllipseButton").find("i").attr("class", "icon-aoi-ellipse");
    $("#aoiDefinedButton").find("i").attr("class", "icon-aoi-polygon");
    $("#aoiEditButton").find("i").attr("class", "icon-aoi-edit");
    $("#aoiSaveButton").find("i").attr("class", "icon-aoi-save");
}


/** *****************************绘制算法部分************************************** */

var AOI_COORD_OFFSET=5; // 绘制时低于该偏差则不绘制
var AOI_SHOW_OFFSET=40; // 闭合交叉时显示的圆圈大小
var theAoiPenColor="rgb(0,0,0)";// 默认绘制的线条颜色
var theAoiFillColor="rgba(0,0,0,0.1)";// 默认绘制的线条颜色
var theAoiStrokeWidth=1;// 默认绘制的线条宽度
var AOI_IS_COMPLETE_POLYGON = true; // 是否已完成多边形绘制(在绘制多边形时才判断)

/**
 * AOI类型枚举定义
 */
var AoiTypeEnum = {
    RECTANGLE:"rectangle", // 矩形
    ELLIPSE : "ellipse", // 圆形
    POLYGON : "polygon"// 多边形
};

/**
 * 绘制函数
 */
AoiDrawAlgorithm = {

    draw:function(canvasId,aoiType){
        var that=this;

        if(!that.initAoi(canvasId)){
            return;
        }
            
        var canvas=document.getElementById(canvasId);
        
        // canvas 的矩形框
        var canvasRect = canvas.getBoundingClientRect();
        // 矩形框的左上角坐标
        var canvasLeft=canvasRect.left;
        var canvasTop=canvasRect.top;

        var layerName=gainAoiLayerName();
        var x=0;
        var y=0;

        // 鼠标点击按下事件，画图准备
        canvas.onmousedown=function(e){
            layerName=gainAoiLayerName(); // 每次按下时新获取一次layer名称
            x = e.clientX-canvasLeft;
            y = e.clientY-canvasTop;

            $("#"+canvasId).addLayer({
                type: aoiType,
                strokeStyle: theAoiPenColor,
                strokeWidth: theAoiStrokeWidth,
                name:layerName,
                fromCenter: false,
                x: x, y: y,
                width: 1,
                height: 1
            });

            $("#"+canvasId).drawLayers();
            $("#"+canvasId).saveCanvas();
            // 鼠标移动事件，画图
            canvas.onmousemove=function(e){
                width = e.clientX-canvasLeft-x;
                height = e.clientY-canvasTop-y;

                $("#"+canvasId).removeLayer(layerName);

                $("#"+canvasId).addLayer({
                    type: aoiType,
                    strokeStyle: theAoiPenColor,
                    strokeWidth: theAoiStrokeWidth,
                    name:layerName,
                    fromCenter: false,
                    x: x, y: y,
                    width: width,
                    height: height
                });

                $("#"+canvasId).drawLayers();
            };
        };

        canvas.onmouseup=function(e){
            canvas.onmousemove=null;

            width = e.clientX-canvasLeft-x;
            height = e.clientY-canvasTop-y;

            $("#"+canvasId).removeLayer(layerName);
            
            if(Math.abs(width)>=AOI_COORD_OFFSET&&Math.abs(height)>=AOI_COORD_OFFSET){
                if(width<0){
                    x=x+width;
                }   
                if(height<0){
                    y=y+height;
                }
                
               $("#"+canvasId).addLayer({
                   type: aoiType,
                   strokeStyle: theAoiPenColor,
                   strokeWidth: theAoiStrokeWidth,
                   name:layerName,
                   fromCenter: false,
                   fillStyle: theAoiFillColor,
                   x: x, y: y,
                   width: Math.abs(width),
                   height: Math.abs(height)
               });
           }

            $("#"+canvasId).drawLayers();
            $("#"+canvasId).saveCanvas();
            aoiGraphs_temp.push({type:aoiType,name:layerName,showName:"",status:true,poLength:0});
        };
    },
    
    drawDefinedAngle:function(canvasId){
        var that=this;

        if(!that.initAoi(canvasId)){
            return;
        }
        
        var canvas=document.getElementById(canvasId);
        
        // canvas 的矩形框
        var canvasRect = canvas.getBoundingClientRect();
        // 矩形框的左上角坐标
        var canvasLeft=canvasRect.left;
        var canvasTop=canvasRect.top;

        var layerName=gainAoiLayerName();
        var x=0;
        var y=0;
        
        var muliPoints = new Array(); // 保存已绘制的点
        var isFirstDraw = true;
        var preLayerName = null; // 正在绘制的多边形的layer名称（由于多边形是由多条线组成的，因此未绘制完成时都用同一个layer）
        var isShowFinish = false;
        var FINISH_SUFIXX = "_finished";
        var isMoved = false; // 是否鼠标按下后移动了？主要是防止用户不自觉地的单击界面时，不要画

        // 鼠标点击按下事件，画图准备
        canvas.onmousedown=function(e){
            if(preLayerName==null){
                layerName=gainAoiLayerName(); // 每次新绘制一个多边形时，获取一次layer名称
                preLayerName=layerName;
            }
            x = e.clientX-canvasLeft;
            y = e.clientY-canvasTop;
            
            if(isFirstDraw){ // 第一次画
                 $("#"+canvasId).addLayer({
                     type: 'line',
                     strokeStyle: theAoiPenColor,
                     strokeWidth: theAoiStrokeWidth,
                     name:preLayerName,
                     fromCenter: false,
                     x1: x, y1: y,
                     x2: x, y2: y                    
                 });
                 muliPoints.push({x:x,y:y});
                
                 $("#"+canvasId).drawLayers();
                 $("#"+canvasId).saveCanvas();
                 isFirstDraw=false;
                 AOI_IS_COMPLETE_POLYGON = false; // 表示开始绘制多边形，此后必须要确保所有线条封闭成已给多边形
            }
            
            // 鼠标移动事件，画图
            canvas.onmousemove=function(e){
                  isMoved = true;
                var x2 = e.clientX-canvasLeft;
                var y2 = e.clientY-canvasTop;
                
                $("#"+canvasId).removeLayer(preLayerName);
                if(isShowFinish){
                    $("#"+canvasId).removeLayer(preLayerName+FINISH_SUFIXX);
                    isShowFinish=false;
                }
                
                var obj = {
                    type: 'line',
                    strokeStyle: theAoiPenColor,
                    strokeWidth: theAoiStrokeWidth,
                    name:preLayerName,
                    fromCenter: false
                 };
                 var p = 0;
                 for (p = 0; p < muliPoints.length; p ++) {
                   obj['x'+(p+1)] = muliPoints[p].x;
                   obj['y'+(p+1)] = muliPoints[p].y;
                 }
                   obj['x'+(p+1)] = x2;
                   obj['y'+(p+1)] = y2;

                $("#"+canvasId).addLayer(obj);

                
                if(muliPoints.length>2){ // 超过2个点才能画多边形
                    if(is_coord_offset(muliPoints[0].x,muliPoints[0].y,x2,y2)){
                         isShowFinish=true;

                     $("#"+canvasId).drawEllipse({
                         layer: true,
                         name:preLayerName+FINISH_SUFIXX,
                         fromCenter: false,
                         strokeStyle: theAoiPenColor,
                         strokeWidth: theAoiStrokeWidth,
                         x: muliPoints[0].x - 20,
                         y: muliPoints[0].y - 20,
                         width: AOI_SHOW_OFFSET,
                         height: AOI_SHOW_OFFSET
                     });
                    }
                }
                $("#"+canvasId).drawLayers();
            };
        };

        canvas.onmouseup=function(e){
            canvas.onmousemove=null;

            var x2 = e.clientX-canvasLeft;
            var y2 = e.clientY-canvasTop;
            
            var isIntersect=false; // 是否相交
            if(muliPoints.length>=3){ // 超过3个点判断是否新画的直线
                 var cPoint={x:x2,y:y2};
                 for (var p = 0; p < muliPoints.length-1; p ++) {
                     if(segmentsIntr(muliPoints[p],muliPoints[p+1],muliPoints[muliPoints.length-1],cPoint)){
                       isIntersect=true;
                       popalert({
                           "content" : "新画的线相交",
                           "icon" : "warning",
                           "ok" : null,
                           "close" : null,
                           "okVal" : "确定",
                           "cancel" : false
                       });
                       break;
                     }
                }
            }
            
            if(!isIntersect){ // 没有相交才代表该点有效，加入到点集合中
               muliPoints.push({x:x2,y:y2});
            }else{
                 // 如果相交，那么肯定是没有结束绘制
                 if(isShowFinish){
                  isShowFinish=false;
                  $("#"+canvasId).removeLayer(preLayerName+FINISH_SUFIXX);
                 }
            }
                
            var obj = {
                type: 'line',
                strokeStyle: theAoiPenColor,
                strokeWidth: theAoiStrokeWidth,
                name:preLayerName,
                fromCenter: false
             };
             
             if(isShowFinish){ // 当完成绘制时，不用绘制最后一个点，因为要使用closed属性直接闭合
                for (var p = 0; p < muliPoints.length-1; p ++) {
                  obj['x'+(p+1)] = muliPoints[p].x;
                  obj['y'+(p+1)] = muliPoints[p].y;
                }
            }else{
                for (var p = 0; p < muliPoints.length; p ++) {
                  obj['x'+(p+1)] = muliPoints[p].x;
                  obj['y'+(p+1)] = muliPoints[p].y;
                }                     
            }
             
            $("#"+canvasId).removeLayer(preLayerName);
            if(!isMoved){
                 muliPoints=new Array();// 清空已绘制完成的点
                 isFirstDraw=true;
                 preLayerName=null;
                 isMoved = false;
                 return;
            }
            
            
            if(isShowFinish){
                $("#"+canvasId).removeLayer(preLayerName+FINISH_SUFIXX);
                isShowFinish=false;
                obj['closed']=true;
                obj['fillStyle']=theAoiFillColor;
                aoiGraphs_temp.push({type:AoiTypeEnum.POLYGON,name:preLayerName,showName:"",status:true,poLength:muliPoints.length-1});
                muliPoints=new Array();// 清空已绘制完成的点
                isFirstDraw=true;
                preLayerName=null;
                isMoved = false;
                AOI_IS_COMPLETE_POLYGON = true; // 所有线条构成封闭多边形，绘制完成
            }

            $("#"+canvasId).addLayer(obj);

            $("#"+canvasId).drawLayers();
            $("#"+canvasId).saveCanvas();
        };
    },
    edit:function(canvasId){
        var that=this;
        if(!that.initAoi(canvasId)){
            return;
        }

        $("#"+canvasId).setLayers({
            draggable:true,
            dblclick:function(layer){ // 双击是删除已绘制的图形方法
              for(var i=0;i<aoiGraphs_temp.length;i++){ // 将删除的对象从临时保存的数组中移除，通过设置status方式
                  if(aoiGraphs_temp[i].name==layer.name){
                      aoiGraphs_temp[i].status=false;
                  }
              }
              $("#"+canvasId).removeLayer(layer);
          }
        }).drawLayers();
        
    },
    save:function(canvasId){
        var that=this;
        if(!that.initAoi(canvasId)){
            return;
        }
        
        // var canvas=document.getElementById(canvasId);
        // canvas 的矩形框
        // var canvasRect = canvas.getBoundingClientRect();
        // 矩形框的左上角坐标
        var canvasWidth=$("#"+canvasId).width();
        var canvasHeight=$("#"+canvasId).height();
        
        var saveGraphs= new Array(); // 待保存到后台的图形
        var aoiGraphs_true =  new Array(); // 真正有效的图形数组
        var graph=null;
        var layer = null;

        for(var i=0;i<aoiGraphs_temp.length;i++){
            if(aoiGraphs_temp[i].status){// 当图形的状态为true表示有效（未被删除）
                layer = $("#"+canvasId).getLayer(aoiGraphs_temp[i].name);
                graph = {
                      type:aoiGraphs_temp[i].type,
                      name:aoiGraphs_temp[i].name,
                      showName:aoiGraphs_temp[i].showName,
                      strokeStyle:layer.strokeStyle,
                      strokeWidth:layer.strokeWidth,
                      fillStyle:layer.fillStyle,
                      x:layer.x,
                      y:layer.y,
                      canvasWidth:canvasWidth,
                      canvasHeight:canvasHeight
                };
                if(aoiGraphs_temp[i].type==AoiTypeEnum.POLYGON){ // 多边形需要保存各个点的坐标
                    graph['poLength']=aoiGraphs_temp[i].poLength;
                    var points = new Array();
                    for(var j=0;j<aoiGraphs_temp[i].poLength;j++){
                        var x=eval("$('#"+canvasId+"').getLayer('"+aoiGraphs_temp[i].name+"').x"+(j+1)+";");
                        var y=eval("$('#"+canvasId+"').getLayer('"+aoiGraphs_temp[i].name+"').y"+(j+1)+";");
                        points.push({x:x,y:y});
                    }
                    graph['points']=points;                    
                }else{ // 矩形和圆形需要保存长度和宽度
                    graph['width']=layer.width;
                    graph['height']=layer.height;
                }
                aoiGraphs_true.push(aoiGraphs_temp[i]); // 只将有效的图形加入
                saveGraphs.push(graph);
            }
        }
        aoiGraphs_temp =  aoiGraphs_true; // 在保存时将临时数组更新为只有效的图形
        aoiGraphs_true = null;

        var inputPara = {
                "projectCode" : $("#projectCode").val(),
                "schemeCode" : $("#schemeCode").val(),
                "aoiGraphs" : JSON.stringify(saveGraphs)
                };
     // 后台保存的即是当前有效的AOI图形信息
        $("#schemeAoiGraphs").val(JSON.stringify(saveGraphs));
        schemeAoiGraphs = saveGraphs; 
        saveGraphs = null;
        
        loading(); // 异步交互时，提示用户处理中
        callJsonData("analysis_saveAoiGraphs.action", inputPara, function(){
            closeLoad();
            $("#aoiSaveButton").find("i").attr("class", "icon-aoi-save");
            });
        
    },
    initAoi:function(canvasId){
        clearAlreadyCheck(false);
        // 在重新定义AOI时，要取消所选择的被试结果
        aoiDataList = null; // 清空之前已绘制的兴趣区数据集
        
        if(!AOI_IS_COMPLETE_POLYGON){
            popalert({
                "content" : "请先绘制完成当前的多边形",
                "icon" : "warning",
                "ok" : null,
                "close" : null,
                "okVal" : "确定",
                "cancel" : false
            });
            return false; // 初始化未完成，不能继续接下来的动作
        }
        
        var canvas=document.getElementById(canvasId);        
        /** 重置事件+让已绘制的图形不再处于编辑状态 */
        canvas.onmousedown=null; 
        canvas.onmousemove=null;
        canvas.onmouseup=null;
        $("#"+canvasId).setLayers({
            draggable:false,
            dblclick:null
        }).drawLayers();
        
        return true;
    }
    
};

/**
 * 每次绘制统计数据时，更新aoiGraphs_temp
 */
function updateAoiGraphs(){
    if(aoiGraphs_temp.length>0){
        if(schemeAoiGraphs!=null && schemeAoiGraphs.length>0){
            var aoiGraphs_true =  new Array(); // 真正有效的图形数组
            for(var i=0;i<aoiGraphs_temp.length;i++){
                for(var j=0;j<schemeAoiGraphs.length;j++){
                    if(aoiGraphs_temp[i].name==schemeAoiGraphs[j].name){ // 只有当aoiGraphs_temp中的图形，真正保存后才证明不是临时编辑绘制的
                        aoiGraphs_temp[i].showName = schemeAoiGraphs[j].showName; // AOI名称要更新
                        aoiGraphs_true.push(aoiGraphs_temp[i]);
                    }
                }
            }
            aoiGraphs_temp =  aoiGraphs_true; 
            aoiGraphs_true = null;
        }
    }
    $("#schemeAoiGraphs").val(JSON.stringify(schemeAoiGraphs));// 更新页面保持的AOI对象,因为AOI会在页面被修改
    AOI_IS_COMPLETE_POLYGON = true; // 即便之前多边形未绘制完成，但由于重新绘制了统计数据，因此该标识也置为完成
}


/**
 * 导出AOI数据
 */
function exportAoiGraphs(){
    /** 准备待导出的数据集 */
    var model = getAlreadyCheckValue('fixData'); // 所有选择的被试数据
    var objs = model.data;
    var worker = model.works;

    /** 待导出的AOI */
    var aoiGraph = schemeAoiGraphs[modifyAoiIndex];
    
    var widthRate = aoiGraph.canvasWidth / $("#myCanvas").width(); // 画布宽的缩放比
    var heightRate = aoiGraph.canvasHeight / $("#myCanvas").height(); // 画布高的缩放比
    var mPoints = new Array(); // 多边形的顶点集合
    if (aoiGraph.type == AoiTypeEnum.POLYGON) {
        for ( var k = 0; k < aoiGraph.poLength; k++) {
            mPoints.push({
                x : aoiGraph.points[k].x + aoiGraph.x,
                y : aoiGraph.points[k].y + aoiGraph.y
            }); // 多边形所有图形，在拖动时只会变化x和y坐标，因此绘制、计算时需要与x和y坐标相加
        }
    }

    /** 判断每个被试的数据是否在AOI中 */
    var retStr = "data:text/csv;charset=utf-8,\ufeff";
    retStr += "兴趣区名称,结果名,开始时间[ms],持续时间[ms],结束时间[ms],X位置[px],Y位置[px],左眼瞳孔平均值,右眼瞳孔平均值,\r\n";
    var split = ",";
    var isContain = false; // 注视点是否在AOI图形内
    for ( var i = 0; i < worker; i++) { // 遍历结果数据集,计算是否所属AOI
        for ( var j = 0; j < objs[i].length; j++) {
            if (aoiGraph.type == AoiTypeEnum.RECTANGLE) {
                isContain = isRectangleContainsPoint(aoiGraph.x, aoiGraph.y, aoiGraph.width, aoiGraph.height, {
                    x : objs[i][j].x * widthRate,
                    y : objs[i][j].y * heightRate
                });
            } else if (aoiGraph.type == AoiTypeEnum.ELLIPSE) {
                // graphs中的x和y是左上角的坐标，因此需要换算到圆形中心坐标
                isContain = isEllipseContainsPoint(aoiGraph.x + aoiGraph.width / 2, aoiGraph.y + aoiGraph.height / 2, aoiGraph.width, aoiGraph.height, {
                    x : objs[i][j].x * widthRate,
                    y : objs[i][j].y * heightRate
                });
            } else if (aoiGraph.type == AoiTypeEnum.POLYGON) {
                isContain = isPolygonContainsPoint(mPoints, {
                    x : objs[i][j].x * widthRate,
                    y : objs[i][j].y * heightRate
                });
            }

            if (isContain) {
                // 格式化导出数据成csv格式
                retStr+=aoiGraph.showName+split;
                retStr+=$("#resultBody").find("tr").eq(i).find("td").eq(0).text()+split;
                retStr+=objs[i][j].fixStart+split+objs[i][j].fixDur+split+(objs[i][j].fixStart+objs[i][j].fixDur)+split;
                retStr+=+Math.floor(objs[i][j].x*100)/100+split+Math.floor(objs[i][j].y*100)/100+split+objs[i][j].LPS+split+objs[i][j].RPS+split+"\r\n";
            }
            isContain = false;
        }
    }

    /** 导出的数据集 */
    var encodedUri = encodeURI(retStr);  
    var save_link = document.createElement("a");  
    save_link.setAttribute("href", encodedUri);  
    var filename = (new Date()).getTime() + '.csv'; // 文件名
    save_link.setAttribute("download", filename);  

    document.body.appendChild(save_link);  

    // save_link.click(); //该方式在客户端嵌入时无法导出
    var event = document.createEvent('MouseEvents');
    event.initMouseEvent('click', true, false, window, 0, 0, 0, 0, 0, false, false, false, false, 0, null);
    save_link.dispatchEvent(event);
}

/**
 * 判断两点x坐标或者y坐标的距离是否超过偏差
 * 
 * @param x1
 * @param y1
 * @param x2
 * @param y2
 * @returns {Boolean}
 */
function is_coord_offset(x1,y1,x2,y2){
    if(Math.abs(x1-x2)<=AOI_COORD_OFFSET && Math.abs(y1-y2)<=AOI_COORD_OFFSET){
        return true;
    }
    return false;
}

/**
 * 获得绘制AOI时的Layer名
 * 
 * @returns {String}
 */
function gainAoiLayerName(){
    return (new Date()).getTime()+".aoi";
}

/** *****************************判断算法部分************************************** */

/**
 * 判断直线是否相交
 * 
 * @param a
 *            点a(和点b相连)
 * @param b
 *            点b(和点a相连)
 * @param c
 *            点c(和点d相连)
 * @param d
 *            点d(和点c相连)
 * @returns {Boolean}
 */
function segmentsIntr(a, b, c, d){  
  
    // 三角形abc 面积的2倍
    var area_abc = (a.x - c.x) * (b.y - c.y) - (a.y - c.y) * (b.x - c.x);  
  
    // 三角形abd 面积的2倍
    var area_abd = (a.x - d.x) * (b.y - d.y) - (a.y - d.y) * (b.x - d.x);   
  
    // 面积符号相同则两点在线段同侧,不相交 (对点在线段上的情况,本例当作不相交处理);
    if ( area_abc*area_abd>=0 ) {  
        return false;  
    }  
  
    // 三角形cda 面积的2倍
    var area_cda = (c.x - a.x) * (d.y - a.y) - (c.y - a.y) * (d.x - a.x);  
    // 三角形cdb 面积的2倍
    // 注意: 这里有一个小优化.不需要再用公式计算面积,而是通过已知的三个面积加减得出.
    var area_cdb = area_cda + area_abc - area_abd ;  
    if (  area_cda * area_cdb >= 0 ) {  
        return false;  
    }  

    /*
     * //计算交点坐标 var t = area_cda / ( area_abd- area_abc ); var dx= t*(b.x -
     * a.x), dy= t*(b.y - a.y); return { x: a.x + dx , y: a.y + dy };
     */
    return true;
  
}

/**
 * 判断任意一点是否在多边形内
 * 
 * @param mPoints
 *            多边形的坐标点
 * @param point
 *            待判断的任意点坐标
 * @returns {Boolean}
 */
function isPolygonContainsPoint(mPoints, point) {  
        var nCross = 0;  
        for (var i = 0; i < mPoints.length; i++) {  
            var p1 = mPoints[i];  
            var p2 = mPoints[(i + 1) % mPoints.length];  
            // 取多边形任意一个边,做点point的水平延长线,求解与当前边的交点个数
            // p1p2是水平线段,要么没有交点,要么有无限个交点
            if (p1.y == p2.y)  
                continue;  
            // point 在p1p2 底部 --> 无交点
            if (point.y < Math.min(p1.y, p2.y))  
                continue;  
            // point 在p1p2 顶部 --> 无交点
            if (point.y >= Math.max(p1.y, p2.y))  
                continue;  
            // 求解 point点水平线与当前p1p2边的交点的 X 坐标
            var x = (point.y - p1.y) * (p2.x - p1.x) / (p2.y - p1.y) + p1.x;  
            if (x > point.x) // 当x=point.x时,说明point在p1p2线段上
                nCross++; // 只统计单边交点
        }  
        // 单边交点为偶数，点在多边形之外 ---
        return (nCross % 2 == 1);  
    }

/**
 * 判断任意一点是否在矩形内
 * 
 * @param x
 *            矩形左上角x坐标
 * @param y
 *            矩形左上角y坐标
 * @param width
 *            矩形宽度
 * @param height
 *            矩形长度
 * @param point
 *            待判断的任意点坐标
 * @returns {Boolean}
 */
function isRectangleContainsPoint(x,y,width,height,point){      
    return (((point.x-x)>0)&&((point.x-x)<width)&&((point.y-y)>0)&&((point.y-y)<height));

}

/**
 * 判断任意一点是否在圆形内
 * 
 * @param x
 *            圆形中心x坐标
 * @param y
 *            圆形中心y坐标
 * @param width
 *            圆形宽度
 * @param height
 *            圆形长度
 * @param point
 *            待判断的任意点坐标
 * @returns {Boolean}
 */
function isEllipseContainsPoint(x,y,width,height,point){
    var focus=0; // 焦距
    if(width > height){ // 根据长轴算焦距和焦点，焦点一定在长轴上
        focus=  Math.sqrt(Math.pow(width/2,2)-Math.pow(height/2,2));         
        // 椭圆中，在椭圆上的点，其和两个焦距的距离之和一定等于长轴长度
      return calcLineDistance(x-focus,y,point.x,point.y)+calcLineDistance(x+focus,y,point.x,point.y) < width?true : false;
  }else{
        focus=  Math.sqrt(Math.pow(height/2,2)-Math.pow(width/2,2));
      return calcLineDistance(x,y-focus,point.x,point.y)+calcLineDistance(x,y+focus,point.x,point.y) < height?true : false;
  }
        
}

/**
 * 计算两点长度
 * 
 * @param x
 * @param y
 * @param x1
 * @param y1
 * @returns
 */
function calcLineDistance(x,y,x1,y1){
    return Math.sqrt(Math.pow(Math.abs(x-x1),2)+Math.pow(Math.abs(y-y1),2));
}

